import json
from typing import Dict, Any
from app.core.config import settings
from redis import Redis

class PubSubService:
    def __init__(self):
        self.redis = Redis(
            host=settings.REDIS_HOST,
            port=settings.REDIS_PORT,
            password=settings.REDIS_PASSWORD,
            decode_responses=True
        )
        self.channel = "websocket_messages"
    
    def publish_message(self, client_id: str, message_type: str, task_id: str, data: Dict[str, Any]):
        """发布消息到Redis通道"""
        message = {
            "client_id": client_id,
            "type": message_type,
            "task_id": task_id,
            "data": data
        }
        self.redis.publish(self.channel, json.dumps(message))

# 创建全局实例
pubsub_service = PubSubService()